﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;

using System.Linq;
using System.Linq.Expressions;
using System.Text;

using ProjectBase.Core;

using $prjsn$.Common;
using $prjsn$.Common.Validation;

namespace $safeprojectname$
{
    public class UniqueRule<TItem> : RuleBase, IValidationRule<TItem>
        where TItem : class, IPersistentObject
    {
        #region members
        private Func<TItem, IEnumerable<TItem>> _compiledExpression;
        IList<string> _uniqueProperties;
        #endregion members

        #region Constructor
        public UniqueRule(Func<TItem, IEnumerable<TItem>> expression, params string[] uniqueProperties)
        {
            _compiledExpression = expression;
            _uniqueProperties = uniqueProperties;
        }
        #endregion Constructor

        #region Validate
        public virtual ValidationResult Validate(TItem item, out ValidationMessage message)
        {
            message = null;
            var existing = CompiledExpression.Invoke(item);
            if (existing.IsEmpty())
            {
                return ValidationResult.IsValid;
            }
            var original = existing.First() as IPersistentObject;
            message = new ValidationMessage(Str.Messages.ItemAlreadyExists3)
            {
                original.GetType().Name,
                original.IDToDisplay,
                UniqueProperties.Localize<TItem>(),
            };
            return ValidationResult.Error;
        }
        #endregion Validate

        #region properties
        public virtual Func<TItem, IEnumerable<TItem>> CompiledExpression
        {
            get { return _compiledExpression; }
            set { _compiledExpression = value; }
        }
        protected virtual IList<string> UniqueProperties
        {
            get { return _uniqueProperties; }
            set { _uniqueProperties = value; }
        }
        #endregion properties
    }
}